//
//  DDAppDelegateResource.m
//  DingDongZP
//
//  Created by LeMac on 17/1/9.
//  Copyright © 2017年 51ledian.com. All rights reserved.
//

#import "DDAppDelegateResource.h"
#import "DDDiscoverViewController.h"
#import "DDWorthViewController.h"
#import "DDMessageListViewController.h"

#import "DDBossDiscoverViewController.h"
#import "DDBossMessageViewController.h"

#import "DDNavigationController.h"
#import "DDLoginManager.h"
#import "DDWelcomeViewController.h"
#import "DDNewIntroViewController.h"

#import "DDLoginUserManager.h"
//#import <Bugtags/Bugtags.h>
#import "DDCheckUpdata.h"

#import "DDContactRequestMessage.h"
#import "DDInterviewReply.h"
#import "DDInterviewMessage.h"
#import "DDUserInfoService.h"
#import "DDBossInfoService.h"
#import "DDBossInfo.h"
#import "DDCommunicatedStore.h"

#import "WXApi.h"
#import <WeiboSDK.h>
#import <GeTuiSdk.h>
#import <RDVTabBarController/RDVTabBarController.h>
#import <UMengAnalytics-NO-IDFA/MobClick.h>
#import "IQKeyboardManager.h" // 键盘监听
#import <RongCallKit/RCCall.h>  // 视频通话相关
#import <RongCallKit/RCCallSingleCallViewController.h>// 视频通话相关
//#import <JSPatch/JPEngine.h>
#import "DDRegisterViewController.h"
#import "DDBossOnlineInterviewAlert.h"
#import "DDChatMessageViewController.h"


@interface DDAppDelegateResource()

@property (nonatomic, strong)RCCallSingleCallViewController *callViewPre;
@property (nonatomic, strong)RCCallSingleCallViewController *callView;
@property(nonatomic , strong)RCCallSession *RcallSession; // 通话实体



@end


@implementation DDAppDelegateResource

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initAppInfo];
    }
    return self;
}

//宣传页
+(void)showNewIntro{
    
    NSArray *coverImageNames = @[@"welcome1", @"welcome2", @"welcome3", @"welcome4", @"welcome5", @"welcome6"];
    
    LDGuiderImgVC *vc = [[LDGuiderImgVC alloc] init];
    vc.guidePicArr = coverImageNames;
    [[UIApplication sharedApplication] keyWindow].rootViewController = vc;
}

//
- (void) initAppInfo {
    
    //设置网络配置
    //    [LDAPPConfigureManager configureManger];
    //初始化校验
    //    [DDVerifyInfoManger shareManger];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
    /** 禁用IQKeyBoard 的类 */
    [[manager disabledDistanceHandlingClasses] addObject:[DDChatMessageViewController class]];
    [[manager disabledDistanceHandlingClasses] addObject:[meSettingFeedBackChat class]];
    
    [DDAPIGenerate sharedInstance].serverType = kNetServerType;
    
    //初始化SDK
    [NSOperation bk_performBlockInBackground:^{
        
        // 友盟
        [MobClick startWithAppkey:kUmengAppKey reportPolicy:REALTIME channelId:nil];
        // 微信
        [WXApi registerApp:kWechatAPP_ID withDescription:@"叮咚快聘"];
        // 微博
        [WeiboSDK registerApp:kWeiboAPP_ID];
        // 融云
        if ([DDAPIGenerate sharedInstance].serverType == kLinkServerTypeOfNormal) {
            
            [[RCIM sharedRCIM] initWithAppKey:kFormalRongCloudAppKey];
            [GeTuiSdk startSdkWithAppId:kFormalGeTuiAppId appKey:kFormalGeTuiAppKey appSecret:kFormalGeTuiSecret delegate:self];
            
        } else {
            
            [[RCIM sharedRCIM] initWithAppKey:kTestRongCloudAppKey];
            [GeTuiSdk startSdkWithAppId:kTestGeTuiAppId appKey:kTestGeTuiAppKey appSecret:kTestGeTuiSecret delegate:self];
        }
        
        [[RCIM sharedRCIM] setUserInfoDataSource:self];
        [RCIM sharedRCIM].receiveMessageDelegate = self;
        [RCIM sharedRCIM].connectionStatusDelegate = self;
        [[RCCallClient sharedRCCallClient] setDelegate:self];
        
        [[RCIM sharedRCIM] registerMessageType:[DDContactRequestMessage class]];
        [[RCIM sharedRCIM] registerMessageType:[DDInterviewReply class]];
        [[RCIM sharedRCIM] registerMessageType:[DDInterviewMessage class]];
        
        [GeTuiSdk clearAllNotificationForNotificationBar];
        
        //        [JPEngine startEngine];
        //rdvLDMainTabBarVC
        id rootTabbarVC = (LDMainTabBarVC *)[UIApplication sharedApplication].keyWindow.rootViewController;
        if ([rootTabbarVC isKindOfClass:[LDMainTabBarVC class]]) {
            
            LDMainTabBarVC *rootVC = (LDMainTabBarVC *)rootTabbarVC;
            rootVC.delegate = self;
        }
        
    } afterDelay:1];
}

#pragma mark - 缓存消息

- (YYCache *)rcUserInfoCache {
    if (!_rcUserInfoCache){
        _rcUserInfoCache = [YYCache cacheWithName:@"rcuserinfo"];
    }
    return _rcUserInfoCache;
}

/// 获取用户的信息并缓存下来，将会在聊天环境中用到。
- (DDUserInfoService *)userService {
    if (!_userService){
        _userService = [[DDUserInfoService alloc] init];
    }
    return _userService;
}

- (DDBossInfoService *)bossService {
    if (!_bossService){
        _bossService = [[DDBossInfoService alloc] init];
    }
    return _bossService;
}

- (void)cacheUserinfo {
    [self.userService queryUserInfo:^(DDUserInfoModel *model) {
        [DDLoginUserManager setWeixin:model.weixin];
        // 保存userid
        [DDLoginUserManager setUserID:model.userid];
    }];
}

- (void)cacheBossInfo {
    [self.bossService queryBossInfoWithSuccessBlock:^(id responseObject) {
        DDBossInfo *model = [DDBossInfo yy_modelWithJSON:responseObject[@"data"]];
        [DDLoginUserManager setWeixin:model.weixin];
        [DDLoginUserManager setUserID:model.userid];
    } failBlock:nil];
}


#pragma mark - GeTui Delegate
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    
    if (payloadData.length < 1) {
        return;
    }
    
    
    //    if ([DDLoginUserManager isLogin]) {
    //
    //        RDVTabBarController *rootvc = (LDMainTabBarVC *)self.window.rootViewController;
    //        //        rootvc.selectedIndex = 2;
    //        NSUInteger n = [[LDAPPConfigureManager configureManger].geTuiMessageArr count];
    //        [rootvc.rdv_tabBarItem setBadgeValue:[NSString stringWithFormat:@"%lu",(unsigned long)n]];
    //    }
}

#pragma mark - 个推 Delegate
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    
    //    NSLog(@"messageId:_%@",messageId);
}

- (void)GeTuiSdkDidOccurError:(NSError *)error {
    
}

#pragma mark - 融云 Delegate
//获取 容云 userid
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    
    [self.rcUserInfoCache objectForKey:userId withBlock:^(NSString * _Nonnull key, NSObject<NSCoding> * object) {
        
        
        NSString *URLString = [[DDAPIGenerate sharedInstance] API:@"query_profile_with_rcid"];
        DDNetWorkManager *manager = [DDNetWorkManager shareManager];
        //clientType 牛人:0 boss:1
        NSNumber *clientType = [userId hasSuffix:@"jobfinder"] ? @(0):@(1);
        NSDictionary *params = @{@"type":clientType,@"id": userId} ;
        
        [manager POST:URLString parameters:params success:^(id responseObject) {
            
            DDLog(@"融云数据:%@", responseObject);
            NSDictionary *infoData = responseObject[@"data"];
            
            if (infoData.count <2) {
                return;
            }
            NSString *name = infoData[@"name"];
            NSString *logo = infoData[@"logo"];
            
            if (!name || [name isEqual:[NSNull null]]) name = @"";
            if (!logo || [logo isEqual:[NSNull null]]) logo = @"";
            
            logo = [DDAPIGenerate imageURLWithPath:logo];
            RCUserInfo *userinfo = [[RCUserInfo alloc] initWithUserId:userId name:name portrait:logo];
            [self.rcUserInfoCache setObject:userinfo forKey:userId];
            completion(userinfo);
            
        } failure:^(id responseObject, NSError *error) {
            completion(nil);
        }];
    }];
    
}
//接收消息的回调方法
- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    
    if ([message.content isKindOfClass:[RCCommandMessage class]]) {
        
        RCCommandMessage *command = (id)message.content;
        if ([command.name isEqualToString:@"setjob"]) {
            
            NSData *data = [command.data dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSString *target = [dict objectForKey:@"target"];
            NSString *job = [dict objectForKey:@"jobid"];
            
            //  self.presentUserID 获取本人的userID
            NSString *typestring;
            if ([DDClientInfoManager clientType] == DDClientTypeBoss) {
                typestring = @"employer";
            }
            else {
                typestring = @"jobfinder";
            }
            NSString *presentUserID = [NSString stringWithFormat:@"%@_%@",[DDLoginUserManager userID], typestring];
            // 存储 Jobid
            NSUserDefaults *savaJobIdUserDefaults = [NSUserDefaults standardUserDefaults];
            [savaJobIdUserDefaults setObject:[NSString stringWithFormat:@"%@",job] forKey:[NSString stringWithFormat:@"%@To%@_JobId",target,presentUserID]];
            [savaJobIdUserDefaults synchronize];
            
            //            [[DDCommunicatedStore sharedStore] setJobId:job withTargetId:target];
        }
    }
}
//容云连接状态
- (void) onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    
    if ([LDAPPConfigureManager configureManger].isRongYunConnect != nil) {
        
        [LDAPPConfigureManager configureManger].isRongYunConnect(status);
    }
}


#pragma mark - 微博delegate

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    
}

#pragma mark - 微信delegate
-(void) onReq:(BaseReq*)req{
    
};

-(void) onResp:(BaseResp*)resp{
    
    //启动微信支付的response
    NSString *payResoult;
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
                
            case 0:
                payResoult = @"微信支付成功";
                break;
            default:
                payResoult = @"微信支付失败";
                break;
        }
    }
    
    WEAKSELF
    NSDictionary *dic= @{@"payResoult":payResoult};
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_PayResult_WeiXing object:weakSelf userInfo:dic];
};


#pragma mark-视频通话代理方法

- (void)didReceiveCall:(RCCallSession *)callSession
{
    self.RcallSession = callSession;
    
    self.callViewPre = [[RCCallSingleCallViewController alloc]initWithIncomingCall:callSession];
    [[RCCall sharedRCCall]presentCallViewController:self.callViewPre];
    
    
    if ([DDClientInfoManager clientType] == DDClientTypeBoss){
        
        //计费查询
        [[RCCall sharedRCCall].currentCallSession setDelegate:self];
        DDBossOnlineInterviewAlert *bossOnlineInterviewAlert = [DDBossOnlineInterviewAlert shareManager];
        
        [bossOnlineInterviewAlert queryInterviewRlues];
    }
}

- (void)didReceiveCallRemoteNotification:(NSString *)callId
                           inviterUserId:(NSString *)inviterUserId
                               mediaType:(RCCallMediaType)mediaType
                              userIdList:(NSArray *)userIdList
                                userDict:(NSDictionary *)userDict {
    
}

- (void)didCancelCallRemoteNotification:(NSString *)callId
                          inviterUserId:(NSString *)inviterUserId
                              mediaType:(RCCallMediaType)mediaType
                             userIdList:(NSArray *)userIdList {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_OnlineInterview_END object:self userInfo:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}

- (void)callDidConnect {
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    self.callView = [[RCCallSingleCallViewController alloc]initWithActiveCall:[RCCall sharedRCCall].currentCallSession];
    [[RCCall sharedRCCall]presentCallViewController:self.callView];
    
    if ([DDClientInfoManager clientType] == DDClientTypeBoss){
        
        /**
         *  Boss 端再次挂上代理  为了走下面的代理方法
         */
        [[RCCall sharedRCCall].currentCallSession setDelegate:self];
        
        /**
         *  动态发起一个在线面试  并对其进行扣费
         */
        DDBossOnlineInterviewAlert *bossOnlineInterviewAlert = [DDBossOnlineInterviewAlert shareManager];
        
        bossOnlineInterviewAlert.emplyoerID = [DDLoginUserManager userID];
        
        NSString *jobfinderID = self.RcallSession.caller;
        NSArray *arrayString = [jobfinderID componentsSeparatedByString:@"_"]; //从字符_中分隔成2个元素的数组  保存邀请只需要纯数字的id
        bossOnlineInterviewAlert.jobfinderID = [NSString stringWithFormat:@"%@",arrayString[0]];
        
        NSUserDefaults *savaJobIdUserDefaults = [NSUserDefaults standardUserDefaults];
        NSString *jobID = [savaJobIdUserDefaults objectForKey:[NSString stringWithFormat:@"%@To%@_employer_JobId",jobfinderID,[DDLoginUserManager userID]]];
        bossOnlineInterviewAlert.jobID = jobID;
        
        [bossOnlineInterviewAlert creatInterviewAndFeededuction];
    }
    
    
}
- (void)callDidDisconnect
{
    /**
     *  视频通话结束
     */
    [[RCCall sharedRCCall]dismissCallViewController:self.callView];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_OnlineInterview_END object:self userInfo:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)remoteUserDidRing:(NSString *)userId
{
    
}
- (void)remoteUserDidInvite:(NSString *)userId
                  mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidJoin:(NSString *)userId
                mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidChangeMediaType:(NSString *)userId
                           mediaType:(RCCallMediaType)mediaType
{
    
}
- (void)remoteUserDidDisableCamera:(BOOL)disabled byUser:(NSString *)userId
{
    
}
- (void)remoteUserDidLeft:(NSString *)userId
                   reason:(RCCallDisconnectReason)reason
{
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)shouldAlertForWaitingRemoteResponse
{
    
}
- (void)shouldRingForIncomingCall
{
    
}
- (void)shouldStopAlertAndRing
{
    
    [[RCCall sharedRCCall]dismissCallViewController:self.callViewPre];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)errorDidOccur:(RCCallErrorCode)error
{
    /**
     *  视频通话错误
     */
    [[RCCall sharedRCCall]dismissCallViewController:self.callView];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_OnlineInterview_ERROR object:self userInfo:nil];
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    
}
- (void)resultForStartServerRecording:(BOOL)startSuccess
                            errorCode:(RCCallErrorCode)errorCode
{
    
}

- (void)resultForStopServerRecording:(BOOL)stopSuccess
                           errorCode:(RCCallErrorCode)errorCode
{
    
}
- (void)resultForFetchServerRecordingStatus:(BOOL)fetchSuccess
                                     status:(BOOL)isRecording
                                  errorCode:(RCCallErrorCode)errorCode
{
    
}


#pragma - RDV delegate
- (void)tabBarController:(RDVTabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    
    RCConnectionStatus status = [[RCIM sharedRCIM] getConnectionStatus];
    
    if (status != ConnectionStatus_Connected) {
        
        [self bk_performBlock:^(id obj) {
            
            [[DDLoginManager sharedManager] loginRongyun:nil failure:nil];
        } afterDelay:0];
    }
    
    //    RDVTabBarController *rootvc = (LDMainTabBarVC *)self.window.rootViewController;
    //
    //    if (rootvc.selectedIndex == 2) {
    //
    //        [[LDAPPConfigureManager configureManger] removeAllGeTuiMessArr];
    //        [rootvc.rdv_tabBarItem setBadgeValue:nil];
    //    }
}

@end
